package sqlanalysisgui.view.handler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;

import sqlanalysisgui.editor.SqlSourceEditor;
import sqlanalysisgui.session.SessionInfo;
import sqlanalysisgui.util.GUIUtils;
import sqlanalysisgui.view.model.TableInfo;
import sqlanalysisgui.view.outline.SqlCrudOutLine;
import sqlanalysisgui.view.search.SearchTableView;


public class SearchTableViewDbClickHandler extends AbstractHandler {
	public final static String ID = "sqlanalysisgui.view.handler.SearchTableViewDbClickHandler";

	private Logger logger = Logger.getLogger(this.getClass());
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		logger.info("프로젝트 클릭!!!");
		// Get the view
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		SearchTableView view = (SearchTableView) page
				.findView(SearchTableView.ID);
		logger.info("view:"+view);
		logger.info("view:"+view.getSite());
		logger.info("view:"+view.getSite().getSelectionProvider());
		// Get the selection
		ISelection selection = view.getSite().getSelectionProvider()
				.getSelection();
		if (selection != null && selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			// If we had a selection lets open the editor
			if (obj != null) {
				TableInfo tableInfo = (TableInfo) obj;
				SessionInfo.setTableInfo(tableInfo);
				
				try {
					logger.info("에디터 페이지 열기");
					logger.info("tableInfo: " + tableInfo);
		        	//파일열기
		        	File file = new File(tableInfo.getSourcePath());
		        	IFileStore fileStore= null;
					try {
						fileStore = EFS.getStore(file.toURI());
					} catch (CoreException e) {
						e.printStackTrace();
						logger.error("에러 발생: " + e);
					}
				
					logger.info("새로운 에디터로 열기");
//		        	page.openEditor(new FileStoreEditorInput(fileStore), EditorsUI.DEFAULT_TEXT_EDITOR_ID);
					ITextEditor openEditor = (ITextEditor) page.openEditor(new FileStoreEditorInput(fileStore), SqlSourceEditor.ID);
		        	
		        	IEditorPart activeEditor = page.getActiveEditor();
		        	if (activeEditor != null) {
		        		SqlSourceEditor sqlSourceEditor =  (SqlSourceEditor) activeEditor;
		        		logger.info("getTitle: " + activeEditor.getTitle());
		        		logger.info("getSite: " + activeEditor.getSite());
		        		logger.info("sqlSourceEditor: " + sqlSourceEditor.getFileSeq());
		        			        		
		        		ITextEditor editor = (ITextEditor) sqlSourceEditor
		        		        .getAdapter(ITextEditor.class);
		 /*       		IDocumentProvider provider = editor.getDocumentProvider();
		        		IDocument document = provider.getDocument(sqlSourceEditor
		        		        .getEditorInput());
		        		ITextSelection textSelection = (ITextSelection) sqlSourceEditor
		        		        .getSite().getSelectionProvider().getSelection();
		        		int offset = textSelection.getOffset();
		        		sqlSourceEditor.getSite().getSelectionProvider().setSelection(textSelection);*/
		        		//setVisibleRegion
		        		
		        /*		final SourceViewer sourceViewer = new SourceViewer(
		        				sqlSourceEditor.parent, null, null, true, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
		        		
		        		StyledText fTextField = sourceViewer.getTextWidget();*/
		        		
		        		//editor.selectAndReveal(3032, 10);
		        		
		        		//라인 위치로 이동
		        		GUIUtils.goToLine(editor, tableInfo.getSourceLineInteger());
		        		
		        		//Line Number Show
		        		String lineNumbers = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER; 
		        		EditorsUI.getPreferenceStore().setValue(lineNumbers, true);
		        		
		        		
		        		//   HashMap map = new HashMap();
		        		 //  MarkerUtilities.setLineNumber(map, tableInfo.getSourceLineInteger());
		        		   
		        		   //MarkerUtilities.createMarker(editor, map, IMarker.TEXT);
		        		
		        		   
		        		   
		        	
/*		        		try {
							int lineNumber = document.getLineOfOffset(offset);
							System.out.println("lineNumber: " + lineNumber);
							System.out.println("lineNumber2: " + document.getNumberOfLines());
							//editor.getAdapter(Control.class)
//							sqlSourceEditor.getSite().getSelectionProvider().getSelection()
						} catch (BadLocationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}*/
		        		
		        		
		        		SqlCrudOutLine sqlCrudOutLineView = (SqlCrudOutLine) page
		        				.findView(SqlCrudOutLine.ID);
		        		
		        		sqlCrudOutLineView.setDataRefresh(tableInfo);
		        		
		        		//page.findEditor(new FileStoreEditorInput(fileStore));
		        	}
		    		
		    		/*
		    		 * 

		ISelection selection= getSelectionProvider().getSelection();
		if (selection instanceof ITextSelection) {
			ITextSelection textSelection= (ITextSelection) selection;
			if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
				markInNavigationHistory();
		}

		StyledText widget= fSourceViewer.getTextWidget();
		widget.setRedraw(false);
		{
			adjustHighlightRange(revealStart, revealLength);
			fSourceViewer.revealRange(revealStart, revealLength);

			fSourceViewer.setSelectedRange(selectionStart, selectionLength);

			markInNavigationHistory();
		}
		
		
public void handleSelection(String selected, ArrayList links){
    if (selected == null) return;
    try {
      int toShow = 0;
      String className;
      Iterator it = links.iterator();
      while (it.hasNext()){
        LinkAttribute la = (LinkAttribute)it.next();
        if (la.getLabel().equals(selected)){
          toShow = getLinkLine(la) - 1;//.getJimpleLink() - 1;
          
          className = la.getClassName();
          findClass(className);
        }
      }
      int selOffset = getLinkToEditor().getDocumentProvider().getDocument(getLinkToEditor().getEditorInput()).getLineOffset(toShow);
      if ((selOffset != -1) && (selOffset != 0)){
        
        if (getLinkToEditor() instanceof JimpleEditor){
          
          ((JimpleEditor)getLinkToEditor()).getViewer().setRangeIndication(selOffset, 1, true);
          SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(getLinkToEditor());
          
        }
        else {
          SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(getLinkToEditor());
          ((AbstractTextEditor)SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()).selectAndReveal(selOffset, 0);
          ((AbstractTextEditor)SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()).setHighlightRange(selOffset, 1, true);
          
        }
      }
    }
    catch(BadLocationException e){
      System.out.println(e.getMessage());    
    }
  }
  
  
  
  
 EditorRegistry editorReg = (EditorRegistry)PlatformUI.getWorkbench().getEditorRegistry();
    EditorDescriptor editor = (EditorDescriptor) editorReg.findEditor(editorId);
    
    
 IEditorPart activeEditor = page.getActiveEditor();
        if (activeEditor != null) {
            // Find the editor reference that relates to this editor input
            IEditorReference[] editorRefs = page.findEditors(activeEditor.getEditorInput(), null, IWorkbenchPage.MATCH_INPUT);
            if (editorRefs.length > 0) {
                workbenchEditorsTracker.setLastActiveEditor(perspective.getId(), editorRefs[0]);
            }
        }    
		    		 * */
				} catch (PartInitException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
		BufferedReader br = null;
		
//		br = new BufferedReader(new FileReader(new File("D:\\\\project\\\\eclipse\\\\workspace\\\\sqlAnalysisGUI\\\\jsp\\\\file_7.jsp")));
		br = new BufferedReader(new FileReader(new File("G:\\프로젝트\\Dropbox\\프로젝트\\NHN_D2 FEST\\참고자료\\workspace\\sqlAnalysisGUI\\jsp\\sub2\\subsub2\\subsub2_3.jsp")));
		String textLine = null;
		StringBuffer planText = new StringBuffer();
		int line = 0;
		while((textLine = br.readLine()) != null){
			planText.append(textLine);
			if(++line == 84){
				System.out.println("textLine: " + textLine);
				System.out.println("length: " + (planText.toString().getBytes().length));
			}
		}
		
	}
}
